package model;

import java.io.File;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.List;

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
/**
 *
 * @author pyin
 */
public class TSManager {

    private static List scripts = new LinkedList();


    public static TestScript getScript(String scriptName, String machine, String buildName) throws InvalidTSException, InvalidVMHostNameException {
        String fullName = scriptName + "[" + machine + "]" + buildName;
        int index = indexOfTS(fullName);
        if (index == -1) {
            return new TestScript(scriptName, machine, buildName);
        } else {
            return (TestScript) scripts.get(index);
        }
    }

    public static TestScript getScript(String name) throws InvalidTSException, InvalidVMHostNameException  {

            int index = indexOfTS(name);
            if (index == -1) {
                String scriptName = name.substring(0, name.indexOf("[") - 1);
                String machine = name.substring(name.indexOf("["), name.indexOf("]") - 1);
                String buildName = name.substring(name.indexOf("["), name.length());
                return new TestScript(scriptName, machine, buildName);
            } else {
                return (TestScript) scripts.get(index);
            }

    }

    private static int indexOfTS(String name) {
        for (int i = 0; i < scripts.size(); i++) {
            TestScript ts = (TestScript) scripts.get(i);
            if (ts.getScriptName().equals(name)) {
                return i;
            }
        }
        return -1;
    }

    public static void clear() {
        scripts.clear();
    }

    public static void main(String[] args) {
//        TestScript ts = TSManager.getScript("Script2", "uep-install", "drop10");
//        ts.run();

//        VMMachine machine = VMMachineFactory.getVMMachine("win03uepinstall");
//        if (machine.revertToSnapshot("STAF") && machine.start()) {
//            System.out.println("machine win03uepinstall started");
//        }
        getAllScriptNames();
    }
    private static List allScriptNames = new ArrayList();

    public static List getAllScriptNames() {
        allScriptNames.clear();
        listFiles(ConfigManager.getScriptPath(), "java");
        return allScriptNames;
    }

    private static void listFiles(String path, String extension) {
        File f = new File(path);
        String[] names = f.list();
        for (int i = 0, n = names.length; i < n; i++) {
            if (new File(names[i]).isDirectory()) {
                listFiles(names[i], extension);
            }
            if (names[i].endsWith(extension)) {
                System.out.println(names[i].toString());
                allScriptNames.add(names[i]);
            }
        }
    }
}
